import {Component} from '@angular/core';
import {IonicPage, NavController, NavParams, ToastController} from 'ionic-angular';
import {Api} from "../../providers/api/api";
import {User} from "../../providers/providers";

/**
 * Generated class for the CustomerManagePage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@IonicPage()
@Component({
  selector: 'page-customer-manage',
  templateUrl: 'customer-manage.html',
})
export class CustomerManagePage {

  pages: Array<any> = [];
  private params: any = {'page': 0, 'size': 20};

  constructor(public navCtrl: NavController,
              public api: Api,
              public user: User,
              public toastCtrl: ToastController,
              public navParams: NavParams) {
    this.params.agencyName = this.user._user.accountName;
  }

  ionViewWillEnter() {
    this.params.page = 0;
    this.pages = [];
    this.getPages();
  }


  ionViewDidLoad() {
    console.log('ionViewDidLoad CustomerManagePage');
  }

  getPages() {
    let reqParam = "?page=" + this.params.page + "&size=" + this.params.size + "&agencyName=" + this.params.agencyName + "&sort=accountName,asc";
    let seq = this.api.get('customers' + reqParam).share();

    seq.subscribe((res: any) => {
      // If the API returned a successful response, mark the user as logged in
      if (res) {
        this.pages = this.pages.concat(res);
      } else {
        this.showToast(res).present();
      }
    }, err => {
      this.showToast(err).present();
      console.error('ERROR', err);
    });
    return seq;
  }


  addCustomer() {
    this.navCtrl.push('CustomerAddPage', {}, {
      animate: true,
      direction: 'forward'
    });
  }


  editCustomer(customer: any) {
    this.navCtrl.push('CustomerAddPage', customer, {
      animate: true,
      direction: 'forward'
    });
  }


  deleteCustomer(customer: any) {
    let seq = this.api.delete('customers/' + customer.id).share();
    seq.subscribe((res: any) => {
      this.params.page = 0;
      this.pages = [];
      this.getPages();
      this.showToast("删除成功！").present()
    }, err => {
      this.showToast("删除失败");
      console.error('ERROR', err);
    });
    return seq;
  }

  showToast(msg) {
    return this.toastCtrl.create({
      message: msg,
      duration: 1000,
      position: 'top'
    });
  }

  openChat(customer: any) {
    this.navCtrl.push('SocketPage', customer, {
      animate: true,
      direction: 'forward'
    });
  }

  doInfinite(infiniteScroll) {
    this.params.page = this.params.page + 1;
    this.getPages();
    setTimeout(() => {
      infiniteScroll.complete();
    }, 500);
  }
}
